package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Set;

/**
 * 入住功能Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-06
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住功能
     *
     * @param id 入住功能主键
     * @return 入住功能
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住功能列表
     *
     * @param checkIn 入住功能
     * @return 入住功能
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住功能
     *
     * @param checkIn 入住功能
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住功能
     *
     * @param checkIn 入住功能
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住功能
     *
     * @param ids 需要删除的入住功能主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住功能信息
     *
     * @param id 入住功能主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        //先判断老人是第一次添加还是已经存在(根据身份证号判断)
        LambdaQueryWrapper<CheckIn> LambdaQueryWrapper = Wrappers.lambdaQuery();
        LambdaQueryWrapper.eq(CheckIn::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
        LambdaQueryWrapper.eq(CheckIn::getStatus, 1);
        CheckIn checkIn = checkInMapper.selectOne(LambdaQueryWrapper);
        if (ObjectUtils.isNotEmpty(checkIn)) {
            throw new RuntimeException("老人已经存在");
        }
        //添加老人基本信息（设置状态，bedNumber，bedId）
        //根据bedId查询对应的bed
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateBed(bed);
        Elder elder = addElderMsg(dto.getCheckInElderDto(), bed);
//        添加合同相关信息(设置老人id，老人姓名
//         ，合同编号（需要生成16位的时间戳以及开头标识），开始时间和结束时间，以及根据时间来判断合同的状态（未生效，已生效）)
        addcontract(elder, dto);
        //添加入住信息
        CheckIn check = addcheckIn(elder, bed, dto);
        //添加入住配置相关信息（设置入住表的id）
        addcheckInConfig(check, bed, dto);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CheckInDetailVo detail(Long id) {
        //根据id查询入住信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //根据id查询老人相应信息,封装vo返回对象
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        //获取 老人的年龄
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.parse(elder.getBirthday(), formatter);
        Integer years =(int) ChronoUnit.YEARS.between(localDate, LocalDate.now());
        // 如果当前日期还未到达生日，则年龄减一
//        if (localDate.isAfter(LocalDate.now().minusYears(years))) {
//            years--;
//        }
        checkInElderVo.setAge(years);
        //再根据入住的id查询老人入住配置信息，封装vo返回对象
        LambdaQueryWrapper<CheckInConfig> checkInConfigQueryWrapper = Wrappers.lambdaQuery();
        checkInConfigQueryWrapper.eq(CheckInConfig::getCheckInId, checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInConfigQueryWrapper);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        //再根据老人入住信息查询老人家属信息，封装vo返回对象
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
        //根据老人id去查询老人合同信息，封装vo返回对象
        LambdaQueryWrapper<Contract> contractQueryWraaper = Wrappers.lambdaQuery();
        contractQueryWraaper.eq(Contract::getElderId, elder.getId());
        Contract contract = contractMapper.selectOne(contractQueryWraaper);
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo(checkInElderVo, elderFamilyVos, checkInConfigVo, contract);
        return checkInDetailVo;
    }

    /**
     * 新增入住配置信息
     *
     * @param check
     * @param bed
     * @param dto
     */
    private void addcheckInConfig(CheckIn check, Bed bed, CheckInApplyDto dto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(check.getId());
        checkInConfigMapper.insertCheckInConfig(checkInConfig);
    }

    /**
     * 新增入住信息
     *
     * @param elder
     * @param bed
     * @param dto
     * @return
     */
    private CheckIn addcheckIn(Elder elder, Bed bed, CheckInApplyDto dto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkInMapper.insertCheckIn(checkIn);
        return checkIn;
    }

    /**
     * 新增合同信息
     *
     * @param elder
     * @param dto
     */

    private void addcontract(Elder elder, CheckInApplyDto dto) {
//        添加合同相关信息(设置老人id，老人姓名
//         ，合同编号（需要生成16位的时间戳以及开头标识），
//         开始时间和结束时间，以及根据时间来判断合同的状态（未生效，已生效）)
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        contract.setContractNumber(contractNo);
        if (contract.getStartDate().isBefore(LocalDateTime.now())) {
            contract.setStatus(0);
        } else if (contract.getStartDate().isAfter(LocalDateTime.now()) && contract.getEndDate().isBefore(LocalDateTime.now())) {
            contract.setStatus(1);
        } else if (contract.getEndDate().isAfter(LocalDateTime.now())) {
            contract.setStatus(2);
        }
        contractMapper.insertContract(contract);
    }

    /**
     * 新增老人信息
     *
     * @param checkInElderDto
     * @param bed
     * @return
     */
    private Elder addElderMsg(CheckInElderDto checkInElderDto, Bed bed) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        LambdaQueryWrapper<Elder> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Elder::getIdCardNo, elder.getIdCardNo());
        Elder selected = elderMapper.selectOne(wrapper);
        if (ObjectUtils.isNotEmpty(selected)) {
            //老人已经存在修改老人信息
            elder.setId(selected.getId());
            elderMapper.updateById(elder);
        } else {
            //新增老人信息
            elderMapper.insert(elder);
        }
        return elder;
    }


}
